package com.action.gulimall.product.service.impl;

import com.action.common.constant.ProductConstant;
import com.action.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.action.gulimall.product.entity.AttrEntity;
import com.action.gulimall.product.service.AttrAttrgroupRelationService;
import com.action.gulimall.product.service.AttrService;
import com.action.gulimall.product.vo.AttrGroupWithAttrsVo;
import com.action.gulimall.product.vo.SpuItemAttrGroupVo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.action.gulimall.product.dao.AttrGroupDao;
import com.action.gulimall.product.entity.AttrGroupEntity;
import com.action.gulimall.product.service.AttrGroupService;
import com.action.common.utils.PageUtils;
import com.action.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        log.debug(JSON.toJSONString(params));
        QueryWrapper<AttrGroupEntity> qw = new QueryWrapper<AttrGroupEntity>();
        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            qw.and((obj)->{
                obj.eq("attr_group_id", key).or()
                        .like("attr_group_name", key);
            });
        }
        if(catelogId==0){
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    qw
            );
            return new PageUtils(page);
        }else{
            //select * from pms_attr_group where catelog_id=? and (attr_group_id=key or attr_group_name like "%key%")
            qw.eq("catelog_id", catelogId);
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    qw);
            return new PageUtils(page);
        }
    }

    @Transactional
    @Override
    public void removeGroupAndRelation(List<Long> longs) {
        //删除分组
        this.baseMapper.deleteBatchIds(longs);
        //删除属性和属性分组的关系记录
        attrAttrgroupRelationService.remove(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .in("attr_group_id", longs));
    }

    @Override
    public List<AttrGroupWithAttrsVo> getAllGroupAttrByCatelogId(Long catelogId) {
        //查询分类下所有的分组
        List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        //查询分类下所有的属性
        List<AttrEntity> attrEntities = attrService.list(new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()));
        //将每个分组的所有属性找出来
        List<AttrGroupWithAttrsVo> attrGroupWithAttrsVos = attrGroupEntities.stream().map(item -> {
            AttrGroupWithAttrsVo attrGroupWithAttrsVo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(item, attrGroupWithAttrsVo);
            List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_group_id", item.getAttrGroupId()));
            if(attrAttrgroupRelationEntities!=null&&attrAttrgroupRelationEntities.size()>0){
                Set<Long> collect = attrAttrgroupRelationEntities.stream()
                        .map(attrAttrgroupRelationEntity -> attrAttrgroupRelationEntity.getAttrId())
                        .collect(Collectors.toSet());
                List<AttrEntity> attrEntityList = new ArrayList<>();
                attrEntities.forEach(attrEntity->{
                    if(collect.contains(attrEntity.getAttrId())){
                        attrEntityList.add(attrEntity);
                    }
                });
                if(attrEntityList.size()>0){
                    log.debug("catelog_id:"+catelogId+",attr_group_id="+item.getAttrGroupId()+",attrEntityList.size="+attrEntityList.size());
                    attrGroupWithAttrsVo.setAttrs(attrEntityList);
                }
            }
            return attrGroupWithAttrsVo;
        }).filter(item->item.getAttrs()!=null).collect(Collectors.toList());
        return attrGroupWithAttrsVos;
    }

    @Override
    public List<SpuItemAttrGroupVo> getAttrGroupWithAttrsBySpuId(Long spuId, Long catalogId) {

        //1、查出当前spu对应的所有属性的分组信息以及当前分组下的所有属性对应的值
        AttrGroupDao baseMapper = this.getBaseMapper();
        List<SpuItemAttrGroupVo> vos = baseMapper.getAttrGroupWithAttrsBySpuId(spuId,catalogId);

        return vos;
    }
}